package c6;

import java.util.ArrayList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 利用ReentrantReadWriteLock实现简单的线程安全的list
 */
public class ReentrantLockListTest2 {
    private ArrayList<String> array = new ArrayList<>();

    private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    private final Lock readLock=lock.readLock();
    private final Lock writeLock=lock.writeLock();

    private void add(String s) {
        writeLock.lock();
        try {
            array.add(s);
        } finally {
            writeLock.unlock();
        }
    }

    private void remove(String s) {
        writeLock.lock();
        try {
            array.remove(s);
        } finally {
            writeLock.unlock();
        }
    }

    private void get(int index) {
        readLock.lock();
        try {
            array.get(index);
        } finally {
            readLock.unlock();
        }
    }
}
